package com.shchuangzhi.smartguard.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.elvishew.xlog.XLog;
import com.shchuangzhi.smartguard.DividerItemDecoration;
import com.shchuangzhi.smartguard.InOutRecordViewAdapter;
import com.shchuangzhi.smartguard.R;
import com.shchuangzhi.smartguard.core.CheckInOutResult;
import com.shchuangzhi.smartguard.core.Consts;
import com.shchuangzhi.smartguard.core.DBHelper;
import com.shchuangzhi.smartguard.core.InOutRecord;
import com.shchuangzhi.smartguard.core.Machine;
import com.shchuangzhi.smartguard.core.Mode;
import com.shchuangzhi.smartguard.core.Notify;
import com.shchuangzhi.smartguard.core.NotifyMessage;
import com.shchuangzhi.smartguard.core.NotifyPrinter;
import com.shchuangzhi.smartguard.core.Student;
import com.shchuangzhi.smartguard.core.StudentState;
import com.shchuangzhi.smartguard.core.Swiper;
import com.shchuangzhi.smartguard.core.TTS;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class InOut extends Fragment {

    private DBHelper dbHelper;
    private Handler handler1;
    private Handler handler2;
    private RecyclerView recyclerView;
    private Button btnQuery;
    private TextView tvInOutCount;
    private TextView tvInOutUploadCount;
    private EditText editQuery;
    private boolean queryClicked = false;
    private List<InOutRecord> list = new ArrayList<>(Consts.MAX_IN_OUT_LIST_SIZE);
    public InOut() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_in_out, container, false);
        recyclerView = (RecyclerView)view.findViewById(R.id.inout_recycler_view);
        LinearLayoutManager layout = new LinearLayoutManager(this.getActivity());
        layout.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layout);
        dbHelper = new DBHelper(this.getActivity());
        list = dbHelper.getInOutRecords(Mode.getInstance().getCurrent());
        final InOutRecordViewAdapter adapter = new InOutRecordViewAdapter(list);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new DividerItemDecoration(this.getActivity(),
                DividerItemDecoration.VERTICAL_LIST));

        handler1 = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                try {
                    NotifyMessage message = (NotifyMessage)msg.obj;
                    if (queryClicked) {
                        list = dbHelper.getInOutRecords(Mode.getInstance().getCurrent());
                        adapter.reload(list);
                        adapter.notifyDataSetChanged();
                    } else {
                        InOutRecord rec = (InOutRecord)message.getData();
                        if (rec != null) {
                            if (list.size() >= Consts.MAX_IN_OUT_LIST_SIZE) {
                                List<InOutRecord> tmp = list;
                                list = new ArrayList<>(Consts.MAX_IN_OUT_LIST_SIZE);
                                list.addAll(tmp.subList(0,50));
                                adapter.reload(list);
                            }
                            list.add(0, (InOutRecord)message.getData());
                            adapter.notifyDataSetChanged();
                        }
                    }
                    queryClicked = false;
                    setTextCountView();
                } catch(Exception e) {
                    XLog.e("", e);
                }
            }
        };

        NotifyPrinter.getInstance().addNotify(Consts.NOTIFY_CHECK_IN_OUT_LIST, new Notify() {
            @Override
            public void notify(NotifyMessage message) {
                handler1.sendMessage(handler1.obtainMessage(Consts.NOTIFY_CHECK_IN_OUT_LIST, message));
            }
        });


        handler2 = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                setTextCountView();
                list = dbHelper.getInOutRecords(Mode.getInstance().getCurrent());
                adapter.reload(list);
                adapter.notifyDataSetChanged();
            }
        };


        NotifyPrinter.getInstance().addNotify(Consts.NOTIFY_INOUT_LIST_SWITCH_MODE, new Notify() {
            @Override
            public void notify(NotifyMessage message) {
                handler2.sendMessage(handler2.obtainMessage(Consts.NOTIFY_INOUT_LIST_SWITCH_MODE, message));
            }
        });

        editQuery = (EditText)view.findViewById(R.id.edit_inout_query);
        editQuery.setOnKeyListener(new android.view.View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    String input = editQuery.getText().toString().trim();
                    if (input.length() >= 10) {
                        editQuery.setText("");
                        String cardNo = input.substring(0, 10).replaceFirst("^0*", "");
                        if(!cardNo.equals("")) {
                            Swiper swiper = dbHelper.getSwiperByCard(cardNo);
                            if (swiper != null) {
                                CheckInOutResult result = swiper.swipe(Mode.getInstance().getCurrent());
                                if (!result.isOk()) {
                                    TTS.get().speak(result.getVoice());
                                }
                            } else {
                                TTS.get().speak(Consts.SPEECH_INVALID);
                                NotifyPrinter.getInstance().notify(
                                        NotifyMessage.info(String.format("%s:%s:2",
                                                Consts.SPEECH_INVALID, cardNo), Consts.NOTIFY_DATA_SYNC, Consts.NOTIFY_DATA_SYC_VIEW_LIST));
                            }
                        }
                    }

                    return true;
                }
                return false;
            }
        });
        btnQuery = (Button)view.findViewById(R.id.btn_inout_query);
        btnQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<InOutRecord> queryResult = new ArrayList<InOutRecord>();
                String cond = editQuery.getText().toString().trim();
                if (!cond.equals("")) {
                    queryResult = dbHelper.queryInOutRecords(Mode.getInstance().getCurrent(), cond);
                } else {
                    queryResult = dbHelper.getInOutRecords(Mode.getInstance().getCurrent());
                }
                adapter.reload(queryResult);
                adapter.notifyDataSetChanged();
                editQuery.setText("");
                queryClicked = true;
            }
        });

        tvInOutCount = (TextView)view.findViewById(R.id.tv_inout_total);
        tvInOutUploadCount = (TextView)view.findViewById(R.id.tv_inout_total_upload);

        setTextCountView();
        return view;
    }

    private void setTextCountView() {
        int[] count = dbHelper.getInOutRecordsCount(Mode.getInstance().getCurrent());
        tvInOutCount.setText(new Integer(count[0]).toString());
        tvInOutUploadCount.setText(new Integer(count[1]).toString());
    }
}
